package com.insight.config.redis;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.async.RedisAsyncCommands;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Lettuce Redis客户端配置，支持异步和连接池等多种用法。
 */
@Configuration
public class LettuceConfig {

    /**
     * Redis主机地址
     */
    @Value("${spring.redis.host}")
    private String host;

    /**
     * Redis端口
     */
    @Value("${spring.redis.port}")
    private int port;

    /**
     * Redis密码（可选）
     */
    @Value("${spring.redis.password:}") // 空字符串默认无密码
    private String password;

    /**
     * Redis数据库索引
     */
    @Value("${spring.redis.database:0}")
    private int database;

    /**
     * 创建Redis客户端Bean
     * @return RedisClient实例
     */
    @Bean(destroyMethod = "shutdown")
    public RedisClient redisClient() {
        RedisURI uri = RedisURI.builder()
                .withHost(host)
                .withPort(port)
                .withDatabase(database)
                .build();

        if (StringUtils.isNotEmpty(password)) {
            uri.setPassword(password.toCharArray());
        }

        return RedisClient.create(uri);
    }

    /**
     * 创建Redis连接Bean
     * @param redisClient Redis客户端
     * @return Redis连接
     */
    @Bean
    public StatefulRedisConnection<String, String> redisConnection(RedisClient redisClient) {
        return redisClient.connect();
    }

    /**
     * 创建异步命令Bean
     * @param connection Redis连接
     * @return 异步命令对象
     */
    @Bean
    public RedisAsyncCommands<String, String> asyncCommands(StatefulRedisConnection<String, String> connection) {
        return connection.async();
    }
}
